package com.literature.search.file.controller;

import com.literature.search.core.common.MessageConstant;
import com.literature.search.core.entity.R.AjaxJson;
import com.literature.search.core.entity.redis.HotWord;
import com.literature.search.core.utils.RedisKeyUtils;
import com.literature.search.core.utils.sp.SpUserUtil;
import com.literature.search.file.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName RedisController
 * @Description TODO
 * @Author abin
 * @Date 2023/3/5 16:41
 * @Version 1.0
 */
@Api(tags = "搜索历史记录管理")
@RestController
@RequestMapping("/redis")
public class RedisController {

    public static final String HOT_WORD_COLLECTION_NAME = "hot_word";

    @Resource
    RedisService redisService;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    MongoTemplate mongoTemplate;

    @ApiOperation(value = "删除用户单个搜索记录",notes = "删除用户单个搜索记录")
    @PostMapping("deleteSearchHistory")
    public AjaxJson deleteSearchHistory(@RequestParam String keyword) {
        redisService.deleteSearchHistoryByValue(keyword);
        return AjaxJson.getSuccess();
    }

    @ApiOperation(value = "删除用户所有搜索历史",notes = "删除用户所有搜索历史")
    @PostMapping("deleteAllSearchHistory")
    public AjaxJson deleteAllSearchHistory() {
        redisService.deleteAllSearchHistory();
        return AjaxJson.getSuccess();
    }

    @ApiOperation(value = "获取用户搜索记录",notes = "获取用户搜索记录")
    @GetMapping("getSearchHistory")
    public AjaxJson getSearchHistory() {
        List<String> list  = redisService.getSearchHistory();
        return AjaxJson.getSuccess(MessageConstant.SUCCESS,list);
    }

    @ApiOperation(value = "获取TOP10热搜关键词",notes = "获取当日TOP10热搜关键词,如果没有则获取昨日TOP10热搜关键词")
    @GetMapping("getSearchHotWord")
    public AjaxJson getSearchHotWord() {
        List<String> list = new ArrayList<>();
        if (redisTemplate.hasKey(RedisKeyUtils.getSearchHotWordKey())) {
            list = redisService.getSearchHotWord();
        }
        else {
            String date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            List<HotWord> hotWords = mongoTemplate.find(new Query(Criteria.where("date").is(date)), HotWord.class,HOT_WORD_COLLECTION_NAME);
            if (hotWords.size() > 0) {
                list = hotWords.stream().map(HotWord::getWord).collect(Collectors.toList());
            }
        }
        return AjaxJson.getSuccess(MessageConstant.SUCCESS, list);
    }
}
